package com.wust.smartcity.common.util;

import com.alibaba.fastjson.JSONObject;
import com.wust.smartcity.common.cache.CacheFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.core.env.PropertiesPropertySource;

/**
 * mq发送工具
 */
public class MqSenderUtil {
    private MqSenderUtil(){}


    /**
     * 此处是通知各个缓存业务对象去更新缓存，复杂的缓存需要通过这种形式去维护数据库与缓存数据的同步
     * @param source
     * @param data
     * @param opt
     */
    public static void cacheSender(String source, Object data, String opt){
        PropertiesPropertySource propertiesPropertySource = CommonUtil.getPropertiesPropertySource("rabbitmqProperties");
        if(propertiesPropertySource == null){
            return;
        }

        PropertiesPropertySource propertiesPropertySource4applicationProperties = CommonUtil.getPropertiesPropertySource("applicationProperties");
        if(propertiesPropertySource4applicationProperties == null){
            return;
        }

        String cacheExchange = "";
        String cacheRoutingKey = "";
        String applicationName = propertiesPropertySource4applicationProperties.getProperty("spring.application.name").toString();
        if("admin-server".equals(applicationName)){
            cacheExchange = propertiesPropertySource.getProperty("spring.rabbitmq.cache4admin.exchange.name").toString();
            cacheRoutingKey = propertiesPropertySource.getProperty("spring.rabbitmq.cache4admin.routing-key").toString();
        }else if("demo-server".equals(applicationName)){
            cacheExchange = propertiesPropertySource.getProperty("spring.rabbitmq.cache4demo.exchange.name").toString();
            cacheRoutingKey = propertiesPropertySource.getProperty("spring.rabbitmq.cache4demo.routing-key").toString();
        }else{
            return;
        }

        if(MyStringUtils.isBlank(MyStringUtils.null2String(cacheExchange))){
            return;
        }

        if(MyStringUtils.isBlank(MyStringUtils.null2String(cacheRoutingKey))){
            return;
        }


        CacheFactory cacheFactory = SpringContextHolder.getBean("cacheFactory");
        if(cacheFactory.getCacheBo(source) == null){
            // 缓存工厂没有配置该持久化对象的缓存，忽略
            return;
        }

        final JSONObject jsonObject = new JSONObject();
        jsonObject.put("category",source);
        jsonObject.put("opt", opt);
        jsonObject.put("data",data);

        RabbitTemplate rabbitTemplate = SpringContextHolder.getBean("rabbitTemplate");
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        rabbitTemplate.convertAndSend(cacheExchange,cacheRoutingKey,jsonObject);
    }
}
